//
//  DemoListCell.swift
//  TXiOSDemoApp
//
//  Created by xicheng on 16/11/25.
//  Copyright © 2016年 xicheng. All rights reserved.
//

import UIKit

class DemoListCell: UITableViewCell {

  fileprivate var iconImageView: UIImageView! = nil
  
  fileprivate var titleLabel:UILabel! = nil
  
  private var _lineView:CALayer! = nil
  
  
  internal var demoModel:DemoModel? = nil {
    
    didSet {
      guard let m = demoModel else {
        return
      }
      config(WidthDemoModel: m)
    }
  
  }
  
  override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    self.prepareView()
  }
  
  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
  
  private func prepareView(){
   
    iconImageView = UIImageView()
    iconImageView.contentMode = .scaleAspectFit
    iconImageView.backgroundColor = UIColor.lightGray
    self.addSubview(iconImageView)
    
    
    titleLabel = UILabel()
    titleLabel.font = UIFont.systemFont(ofSize: 16)
    titleLabel.textColor = UIColor.black
    titleLabel.textAlignment = .left
    self.addSubview(titleLabel)
    
    _lineView = CALayer()
    _lineView.backgroundColor = UIColor.navigationLineColor().cgColor
    self.layer.addSublayer(_lineView)
  
  }
  
  func config(WidthDemoModel model:DemoModel){
    iconImageView.frame = CGRect(x: 0, y: 0, width: kMainScreenWidth, height: kMainScreenWidth * CGFloat(model.picHeight) / CGFloat(model.picWidth))
    if let picUrl = model.picUrl ,  let url =  URL.init(string: picUrl) {
      iconImageView.tx_setImage(WithURL: url)
    }
    titleLabel.text = model.title
    titleLabel.sizeToFit()
    titleLabel.frame = CGRect(x: 12, y: iconImageView.frame.bottom + 12, width: 240, height: titleLabel.frame.height)
    _lineView.frame = CGRect(x: 0, y: titleLabel.bottom + 12, width: kMainScreenWidth, height: 10)
  }
  
  
  static func calculateHeight(WithMode model:DemoModel)->CGFloat{
    return kMainScreenWidth * CGFloat(model.picHeight) / CGFloat(model.picWidth) + 50
  }
  
  
}
